package com.net.xpay.partner.secutiry;


import com.net.xpay.common.domain.partner.Partner;
import com.net.xpay.common.enums.user.ClientFrom;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.time.LocalDateTime;

@Getter
@Setter
public class Operator extends AbstractAuthenticationToken {
    //当前登陆的状态,已登陆或者只是微信/qq/weibo等登陆.
    private OperatorStatus status;

    //以下是账号的信息
    private Long partnerId;

    private ClientFrom clientFrom;

    private LocalDateTime time;

    private Boolean fromRememberMe;

    //以下是第三方登陆的信息
    private String openPlatform; //openId的平台:qq/weChat/weibo

    private String openId; //第三方登陆的昵称

    private String openIdTime; //openId登陆时间


    public Operator(Partner partner, FormLoginToken token) {
        super(null);
        setAuthenticated(true);

        this.status = OperatorStatus.NORMAL_LOGIN;
        this.partnerId = partner.getId();

        this.clientFrom = token.getClientFrom();
        this.time = token.getTime();
        this.fromRememberMe = false;
    }

    public Operator(Partner partner, ClientFrom clientFrom) {
        super(null);
        setAuthenticated(true);

        this.status = OperatorStatus.NORMAL_LOGIN;
        this.partnerId = partner.getId();
        this.clientFrom = clientFrom;
        this.time = LocalDateTime.now();
        this.fromRememberMe = true;
    }

    public static Operator getCurrentOperator() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return null;
        } else if (authentication instanceof Operator) {
            return (Operator) authentication;
        } else {
            return null;
        }
    }

    @Override
    public Object getCredentials() {
        return partnerId;
    }

    @Override
    public Object getPrincipal() {
        return partnerId;
    }
}
